package com.example.Arithmetic.Arithmetic;

import com.example.Arithmetic.Arithmetic.Port.Queue;

import java.util.Iterator;

/**
 * 日期：2023/10/12
 * 时间：9:29
 * 描述：基于链表实现的队列
 */
public class LikendListQueue<E> implements Queue<E>, Iterable<E> {
    //新建一个哨兵节点，head指向哨兵
    Node head = new Node<>(null, null);
    Node tail = head;
    private int size;
    private int capactiy=Integer.MAX_VALUE;

    public LikendListQueue() {
        tail.next = head;
    }

    public LikendListQueue(int capactiy) {
        this.capactiy=capactiy;
    }
    private static class Node<E> {
        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
        private E value;
        private Node<E> next;
    }


    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }
        Node<E> added = new Node<>(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        Node next = head.next;
        head.next = next.next;
        if (next == tail) {
            tail.next = head;
        }
        size--;
        return (E) next.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return (E) head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size==capactiy;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

}
